package com.itheima.health.controller;


import com.itheima.health.dto.SetmealDTO;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.aliyunoss.AliyunUtils;
import com.itheima.health.utils.redis.RedisUtil;
import com.itheima.health.utils.resources.RedisConstant;
import com.itheima.health.utils.resources.UploadUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
public class SetMealController {
    @Reference
    private SetmealService setmealService;

    @PostMapping("setmeal/findPage")
    public Result findPage(@RequestBody QueryPageBean queryPageBean) {
        return new Result(setmealService.findPage(queryPageBean));
    }
    @PostMapping("setmeal/upload")
    public Result upload (@RequestParam("imgFile") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String uuidFilename = UploadUtils.generateRandonFileName(originalFilename);
        AliyunUtils.uploadMultiPartFileToAliyun(file.getBytes(),uuidFilename);
        System.out.println("图片上传云服务器成功，图片ID暂存Radis-Set集合");
        // 上传好阿里云图片之后 我们将图片存储到redis set 集合中
        //  将上传到阿里云的图片文件 保存在redis中
        // 将上传图片 保存到集合中  并且将图片保留24小时  设置过期时间。
        RedisUtil.addToSet(RedisConstant.ALL_SETMEAL_PIC_SET,uuidFilename);
        RedisUtil.set(RedisConstant.SINGLE_PIC+uuidFilename,uuidFilename,1, TimeUnit.MINUTES);//一分钟后删除Redis缓存
        return new Result(uuidFilename);//  一定要把阿里云上的文件名  回送给客户端 ，因为添加套餐时 需要存储到数据库的图片路径

    }
    @PostMapping("setmeal/add")
    public Result add(@RequestBody SetmealDTO setmealDTO) {
        setmealService.saveSetemal(setmealDTO);
        RedisUtil.removeSetMember(RedisConstant.ALL_SETMEAL_PIC_SET,setmealDTO.getImg());
        RedisUtil.delete(RedisConstant.SINGLE_PIC+setmealDTO.getImg());
        System.out.println("套餐保存成功，删除set集合ID");
        return new Result(setmealService.add(setmealDTO));
    }

    @GetMapping("setmeal/findChecked/{id}")
    public Result findChecked(@PathVariable int id) {
        return new Result(setmealService.findChecked(id));
    }




}
